package com.example.hotelsystem.controller;

import code.CodeError;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hotelsystem.entity.Code;
import com.example.hotelsystem.entity.User;
import com.example.hotelsystem.entity.UserRole;
import com.example.hotelsystem.result.Result;
import com.example.hotelsystem.service.UserRoleService;
import com.example.hotelsystem.service.UserService;
import com.example.hotelsystem.utils.CodeUtil;
import com.example.hotelsystem.utils.UUIDGenrateUtil;
import com.example.hotelsystem.utils.VerifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "登录控制器")
@CrossOrigin
public class LoginController {


    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RedisTemplate redisTemplate;


    @GetMapping("/")
    public String hello(){
        return "你好，恭喜您代理成功";
    }


    @ApiOperation("生成验证码")
    @GetMapping("/getcode")
//    @ResponseBody
    public void getCode(HttpServletResponse response) {
        try{
            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.
                            getRequestAttributes()).getRequest();
            HttpSession session=request.getSession();//创建session对象
            //利用图片工具生成图片
            //第一个参数是生成的验证码，第二个参数是生成的图片
            Object[] objs = VerifyUtil.createImage();
            String only = String.valueOf(UUID.randomUUID());
            redisTemplate.opsForValue().set(only+"code",objs[0], 3, TimeUnit.MINUTES);
//            //将验证码存入Session
//            session.setAttribute("imageCode",objs[0]);

            System.out.println("验证码存进去的时候"+objs[0]);
            //将图片输出给浏览器
            BufferedImage image = (BufferedImage) objs[1];
            response.setHeader("Access-Control-Expose-Headers","only");
            response.setHeader("only",only);
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @ApiOperation("用户登录接口")
    @ResponseBody
    @PostMapping("/login")
    public Result Login(@RequestParam("username")String username, @RequestParam("password")String password,String code,String only){
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.
                        getRequestAttributes()).getRequest();
        System.out.println("登录时候的"+redisTemplate.opsForValue().get(only+"code").toString());
        if(redisTemplate.opsForValue().get(only+"code").toString()==null){
            return Result.error(CodeError.GET_CODE_AGAIN,"请重新获取验证码");
        }else {
         Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try{
            if(redisTemplate.opsForValue().get(only+"code").toString().equalsIgnoreCase(code)){
            subject.login(token);
            User user=userService.getOne(new QueryWrapper<User>().eq("username", username));
            user.setPassword(null);

            return Result.success("登录成功",user);
            }else {
                return Result.error(CodeError.CODE_ERROR,"验证码错误");
            }
        }catch (UnknownAccountException e){//用户名不存在
            return Result.error(CodeError.USER_NOT_FOUND,"用户名不存在");
        }catch (IncorrectCredentialsException e){
            return Result.error(CodeError.PASSWORD_ERROR,"密码错误");
        }
        }
    }

    @ApiOperation("不用验证码的后台登录接口")
    @ResponseBody
    @PostMapping("/managerLogin")
    public Result ManagerLogin(@RequestParam("username")String username, @RequestParam("password")String password){

            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            try{
                subject.login(token);
                User user=userService.getOne(new QueryWrapper<User>().eq("username", username));
                UserRole userRole = userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
                if(userRole.getRoleId()!=1L){
                    return Result.error("您没有权限进入后台");
                }
                return Result.success("登录成功",user);
            }catch (UnknownAccountException e){//用户名不存在
                return Result.error(CodeError.USER_NOT_FOUND,"用户名不存在");
            }catch (IncorrectCredentialsException e){
                return Result.error(CodeError.PASSWORD_ERROR,"密码错误");
            }
        }


    @ApiOperation("用户退出注销接口")
    @PostMapping("/logout")
    public Result Logout(){
        SecurityUtils.getSubject().logout();
        return Result.success("注销成功");
    }
}
